package com.auth.project.cn.util;

/**
 * 雪花算法
 * <p>核心思想就是：使用一个 64 bit 的 long 型的数字作为全局唯一id。在分布式系统中的应用十分广泛，且ID 引入了时间戳，基本上保持自增的.
 * 优点：1.高性能高可用：生成时不依赖于数据库，完全在内存中生成;2.容量大：每秒中能生成数百万的自增ID;3.ID自增：存入数据库中，索引效率高
 * 缺点：依赖与系统时间的一致性，如果系统时间被回调，或者改变，可能会造成id冲突或者重复
 * </p>
 */
public class Snowflake {

    /**
     * 起始时间戳2020-07-10 14:30
     */
    private static final long START_TIMESTAMP = 1594362600000L;

    /*每一部分占用的位数*/
    /**
     * 序列号占用的位数
     */
    private final static long SEQUENCE_BIT = 12;
    /**
     * 机器标识占用的位数
     */
    private final static long MACHINE_BIT = 5;
    /**
     * 数据中心占用的位数
     */
    private final static long DATA_CENTER_BIT = 5;

    /*每部分的最大值*/
    /**
     * 序列号最大值
     */
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
    /**
     * 机器标识符最大值
     */
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
    /**
     * 数据中心最大值
     */
    private final static long MAX_DATA_CENTER_NUM = -1L ^ (-1L << DATA_CENTER_BIT);

    /**
     * 每一部分向左的位移
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATA_CENTER_BIT;

    /**
     * 数据中心(或机房ID)
     */
    private long datacenterId;
    /**
     * 机器标识
     */
    private long machineId;
    /**
     * 序列号
     */
    private long sequence = 0L;
    /**
     * 上一次时间戳
     */
    private long lastTimestamp = -1L;

    public Snowflake(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATA_CENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATA_CENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    public synchronized long nextId() {
        long currentTimestamp = getNewTimestamp();
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("Clock has moved backwards. Refusing to generate id");
        }
        if (currentTimestamp == lastTimestamp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currentTimestamp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastTimestamp = currentTimestamp;

        return (currentTimestamp - START_TIMESTAMP) << TIMESTMP_LEFT    //时间戳部分
                | datacenterId << DATACENTER_LEFT                       //数据中心部分
                | machineId << MACHINE_LEFT                             //机器标识部分
                | sequence;                                             //序列号部分
    }

    private long getNextMill() {
        long mill = getNewTimestamp();
        while (mill <= lastTimestamp) {
            mill = getNewTimestamp();
        }
        return mill;
    }

    private long getNewTimestamp() {
        return System.currentTimeMillis();
    }

}
